package com.mogist.hqc.module.place.ui

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.net.Uri
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import butterknife.OnClick
import butterknife.Optional
import cn.jzvd.Jzvd
import com.allure.lbanners.LMBanners
import com.allure.lbanners.adapter.LBaseAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.mogist.hqc.R
import com.mogist.hqc.base.BaseMVPActivity
import com.mogist.hqc.entitys.BaseModel
import com.mogist.hqc.entitys.response.ProductDetailItemVo
import com.mogist.hqc.entitys.response.TypeDetailVo
import com.mogist.hqc.module.common.ui.CommentListActivity
import com.mogist.hqc.module.place.contract.ScenicContract
import com.mogist.hqc.module.place.presenter.ScenicPresenter
import com.mogist.hqc.module.product.adapter.ProductDetailAdapter
import com.mogist.hqc.mvp.HttpDto
import com.mogist.hqc.util.Constant
import com.mogist.hqc.util.Util
import com.mogist.hqc.view.PlayImageView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_scenic_detail.*
import org.jetbrains.anko.contentView
import talex.zsw.basecore.util.BitmapTool
import talex.zsw.basecore.util.IntentTool
import talex.zsw.basecore.util.MapTool
import talex.zsw.basecore.util.RegTool
import talex.zsw.basecore.util.glide.GlideTool
import talex.zsw.basecore.view.dialog.sweetalertdialog.SweetAlertDialog
import talex.zsw.basecore.view.other.RxToast
import talex.zsw.basecore.view.recyleview.DividerItemDecoration
import talex.zsw.basecore.view.recyleview.FullyLinearLayoutManager

/**
 * 作用：地点详情
 * 作者：赵小白 email:vvtale@gmail.com  
 * 修改人：
 * 修改时间：
 * 修改备注：
 */
class ScenicActivity : BaseMVPActivity<ScenicContract.Presenter>(), ScenicContract.View
{

    private var id = ""
    override fun initArgs(intent: Intent)
    {
        intent.getStringExtra("id")
                ?.let {
                    id = it
                }
    }

    override fun initView()
    {
        setContentView(R.layout.activity_scenic_detail)
        mPresenter = ScenicPresenter(this)
    }

    override fun initData()
    {
        //        mTitleBar.setRightIV(R.drawable.i_more) {
        //        }
        initRecyclerView()
        if (RegTool.isEmpty(id))
        {
            showDialog(SweetAlertDialog.ERROR_TYPE,
                       "获取地点详情失败",
                       "请稍后重试",
                       "确定",
                       null,
                       finishListener,
                       null)
        }
        else
        {
            getRouteDetail(id)
        }
    }

    @Optional
    @OnClick(R.id.mLLNav,
             R.id.mLLPhone,
             R.id.mLLCar,
             R.id.mLLComment,
             R.id.mTvToComment,
             R.id.mIvComment,
             R.id.mTvComment,
             R.id.mIvShare,
             R.id.mIvStar,
             R.id.mTvStar,
             R.id.mIvClose,
             R.id.mIvVideoClose)
    fun onViewClicked(view: View)
    {
        if (!isFastClick)
        {
            when (view.id)
            {
                R.id.mIvClose                                                        ->
                {
                    finish()
                }
                R.id.mLLNav                                                          ->
                { // 导航
                    if (RegTool.isEmpty(lat) || RegTool.isEmpty(lon))
                    {
                        if (MapTool.isInstallBaidu())
                        {
                            MapTool.baiduNaviActivity(this@ScenicActivity, lat, lon)
                        }
                        else
                        {
                            MapTool.baiduMapWeb(this@ScenicActivity, lat, lon)
                        }
                    }
                    else
                    {
                        if (MapTool.isInstallBaidu())
                        {
                            val intent = Intent()
                            intent.data =
                                    Uri.parse("baidumap://map/geocoder?src=andr.baidu.openAPIdemo&address=${address}")
                            startActivity(intent)
                        }
                        else
                        {
                            val url =
                                    "http://api.map.baidu.com/geocoder?address=${address}&output=html&src=webapp.baidu.openAPIdemo"
                            val intent = Intent(Intent.ACTION_VIEW)
                            intent.data = Uri.parse(url)
                            startActivity(intent)
                        }
                    }
                }
                R.id.mLLPhone                                                        ->
                { // 地点电话
                    start(IntentTool.getDialIntent(mobile))
                }
                R.id.mLLCar                                                          ->
                { // 租车
                    start(IntentTool.getWebIntent(Constant.RENT_CAR))
                }
                R.id.mLLComment, R.id.mTvToComment, R.id.mIvComment, R.id.mTvComment ->
                { // 评论
                    val intent = Intent(this@ScenicActivity, CommentListActivity::class.java)
                    intent.putExtra("id", id)
                    intent.putExtra("type", 1)
                    start(intent)
                    overridePendingTransition(R.anim.activity_bottom_open, 0)
                }
                R.id.mIvStar, R.id.mTvStar                                           ->
                { // 收藏
                    //type:COL收藏 NOCOL取消收藏 colType:PLACE地点ROUTE线路PRODUCT产品
                    val body = BaseModel(true)
                    body.type = "COL"
                    body.colType = "PLACE"
                    body.pdtId = id
                    mPresenter.getData(HttpDto(Constant.COLLECT_ADD,
                                               body,
                                               true).setShowError(false))
                }
                R.id.mIvShare                                                        ->
                { // 地点分享
                    showShareDialog(Util.createScreenShotBitmap(this@ScenicActivity,
                                                                BitmapTool.view2Bitmap(contentView)))
                }
                R.id.mIvVideoClose                                                   ->
                { // 关闭视频区域
                    mJzvdStd.mediaInterface?.pause()
                    mJzvdStd.onStatePause()
                    mRLVideo.visibility = View.GONE
                    mIvVideoClose.visibility = View.GONE
                }
            }
        }
    }

    override fun onPause()
    {
        super.onPause()
        Jzvd.releaseAllVideos()
        mLMBanners.stopImageTimerTask()
    }

    override fun onBackPressed()
    {
        if (mRLVideo.visibility == View.VISIBLE)
        {
            mJzvdStd.mediaInterface?.pause()
            mJzvdStd.onStatePause()
            mRLVideo.visibility = View.GONE
            mIvVideoClose.visibility = View.GONE
            return
        }
        if (Jzvd.backPress())
        {
            return
        }
        super.onBackPressed()
    }

    // --------------- 获取地点详情 ---------------
    private fun getRouteDetail(id: String)
    {
        this.id = id
        val body = BaseModel()
        body.projectId = id
        mPresenter.getData(HttpDto(Constant.TYPE_DETAIL, body).setType(HttpDto.GET))
    }

    var lat = ""
    var lon = ""
    var address = ""
    var mobile = ""
    override fun bindDetail(data: TypeDetailVo)
    {
        bindBanner(data.platfromProject)
        lat = data.platfromProject.latitude
        lon = data.platfromProject.longitude
        address = data.platfromProject.proAddress
        mobile = data.platfromProject.mobile
        if (RegTool.isEmpty(mobile))
        {
            mIvPhone.setBackgroundResource(R.drawable.shape_gray_oval)
            mIvPhone.setImageResource(R.drawable.i_phone)
            mLLPhone.isEnabled = false
        }
        mTvTitle.text = data.platfromProject.proName
        if (RegTool.isNotEmpty(data.platfromProject.tag))
        {
            val strs =
                    data.platfromProject.tag.split("[;,/，、|]".toRegex())
                            .dropLastWhile { it.isEmpty() }
                            .toTypedArray()
            mLLTag.visibility = View.VISIBLE
            mTvTag1.text = strs[0]
            if (strs.size > 1)
            {
                mTvTag2.text = strs[1]
                if (strs.size > 2)
                {
                    mTvTag3.text = strs[2]
                }
                else
                {
                    mTvTag3.visibility = View.GONE
                }
            }
            else
            {
                mTvTag2.visibility = View.GONE
                mTvTag3.visibility = View.GONE
            }
        }
        else
        {
            mLLTag.visibility = View.GONE
        }
        mTvAddress.text = data.platfromProject.proAddress
        mTvComment.text = data.platfromProject.sayNum.toString()
        // 项目详情
        listData = arrayListOf()
        for (entity in data.projectDetailList)
        {
            addItem(entity.type, entity.conUrl, entity.videoUrl)
        }
        mAdapter.replaceData(listData)
    }

    private fun addItem(type: String?, info: String?, video: String?)
    { // 0:Tab  1:图片  2:文字  3:视频  4:行程
        if (type == "img")
        {
            listData.add(ProductDetailItemVo(1, info))
        }
        else if (type == "text")
        {
            listData.add(ProductDetailItemVo(2, info))
        }
        else if (type == "video")
        {
            val item = ProductDetailItemVo(3, info)
            item.videoUrl = video
            listData.add(item)
        }
    }

    // --------------- RecyclerView ---------------
    private val mAdapter = ProductDetailAdapter(arrayListOf())
    private var listData: ArrayList<ProductDetailItemVo> = arrayListOf()
    private fun initRecyclerView()
    {
        mRecyclerView.addItemDecoration(DividerItemDecoration(this@ScenicActivity,
                                                              DividerItemDecoration.VERTICAL_LIST,
                                                              R.color.transparent,
                                                              0,
                                                              true))
        mRecyclerView.layoutManager = FullyLinearLayoutManager(this@ScenicActivity)
        mRecyclerView.adapter = mAdapter
        mRecyclerView.isNestedScrollingEnabled = false
    }

    // --------------- Banner ---------------
    var curVideoUrl = ""

    private fun bindBanner(vo: TypeDetailVo.PlatfromProjectEntity)
    {
        val list = arrayListOf<TypeDetailVo.PlatfromProjectEntity>()
        list.add(vo)
        //参数设置
        if (list.isNotEmpty())
        {
            mLMBanners.setAdapter(UrlImgAdapter(this@ScenicActivity), list as List<Nothing>?)
            mLMBanners.startImageTimerTask()
            mLMBanners.setCanLoop(true)
        }
    }

    inner class UrlImgAdapter(private val mContext: Context) : LBaseAdapter<TypeDetailVo.PlatfromProjectEntity>
    {
        override fun getView(lBanners: LMBanners<*>, context: Context, position: Int, data: TypeDetailVo.PlatfromProjectEntity): View
        {
            val view =
                    LayoutInflater.from(mContext)
                            .inflate(R.layout.item_banner, null)
            val play = view.findViewById(R.id.mPlayImageView) as PlayImageView
            play.setData(data.posterImg, data.proVideo) { img, video ->
                if (curVideoUrl == video)
                {
                }
                else
                {
                    if (RegTool.isEmpty(curVideoUrl))
                    {
                        mJzvdStd.setUp(video, "")
                    }
                    else
                    {
                        mJzvdStd.changeUrl(video, "", 0L)
                    }
                    if (RegTool.isEmpty(img))
                    {
                        try
                        {
                            Glide.with(this@ScenicActivity)
                                    .setDefaultRequestOptions(RequestOptions().frame(0).centerCrop().error(
                                                    ColorDrawable(Color.BLACK)).placeholder(
                                                    ColorDrawable(Color.BLACK)))
                                    .load(video)
                                    .into(mJzvdStd.thumbImageView)
                        }
                        catch (e: Exception)
                        {
                            e.printStackTrace()
                        }
                    }
                    else
                    {
                        GlideTool.loadImg(mJzvdStd.thumbImageView, img, ColorDrawable(Color.BLACK))
                    }
                    curVideoUrl = video
                }
                mRLVideo.visibility = View.VISIBLE
                mIvVideoClose.visibility = View.VISIBLE
                mJzvdStd.startVideo()
            }
            return view
        }
    }

    override fun onResume()
    {
        if (mLMBanners != null && mLMBanners.itemCount > 1)
        {
            mLMBanners.startImageTimerTask()
        }
        super.onResume()
    }

    override fun onDestroy()
    {
        if (mLMBanners != null)
        {
            mLMBanners.clearImageTimerTask()
        }
        super.onDestroy()
    }

    override fun collectSuccess()
    {
        mIvStar.setImageResource(R.drawable.i_star_yes)
    }

    // --------------- 分享 ----------------
    private var shareDialog: Dialog? = null
    private var dImage: ImageView? = null
    private fun showShareDialog(bitmap: Bitmap)
    {
        shareDialog
                ?: let {
                    shareDialog = Dialog(this@ScenicActivity, R.style.dialog)
                    shareDialog?.setContentView(R.layout.dialog_share)
                    shareDialog?.setCanceledOnTouchOutside(false)
                    val display = window.windowManager.defaultDisplay
                    val layoutParams: WindowManager.LayoutParams = shareDialog?.window!!.attributes
                    layoutParams.width = (display.width * 0.8f).toInt()
                    layoutParams.height = (display.height * 0.9f).toInt()
                    shareDialog?.window!!.attributes = layoutParams
                    dImage = shareDialog?.findViewById(R.id.dImage)

                    shareDialog?.findViewById<TextView>(R.id.dTvSure)
                            ?.setOnClickListener {
                                showDialog()
                                Observable.just(bitmap)
                                        .subscribeOn(Schedulers.io())
                                        .map { v ->
                                            Uri.parse(MediaStore.Images.Media.insertImage(
                                                    contentResolver,
                                                    v,
                                                    null,
                                                    null))
                                        }
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .subscribe({ uri ->
                                                       disDialog()
                                                       val shareIntent = Intent()
                                                       shareIntent.action = Intent.ACTION_SEND
                                                       shareIntent.putExtra(Intent.EXTRA_STREAM,
                                                                            uri)
                                                       shareIntent.type = "image/*"
                                                       start(Intent.createChooser(shareIntent,
                                                                                  "分享到"))
                                                       shareDialog?.dismiss()
                                                   }) { t ->
                                            t.printStackTrace()
                                            disDialog()
                                            RxToast.error("分享失败")
                                        }
                            }
                    shareDialog?.findViewById<TextView>(R.id.dTvCancel)
                            ?.setOnClickListener {
                                bitmap.recycle()
                                shareDialog?.dismiss()
                            }
                }
        dImage?.setImageBitmap(bitmap)
        shareDialog?.show()
    }
}